package com.ke.service.impl;

import com.ke.dao.ShopRepository;
import com.ke.pojo.BaseResp;
import com.ke.pojo.Shop;
import com.ke.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author bochen
 */
@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    ShopRepository shopRepository;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public BaseResp findProductById(Integer id) {
        Optional<Shop> shop=shopRepository.findById(id);
        if (shop.isPresent()){
            return new BaseResp(0,"ok",shop);
        }
        return null;
    }

    @Override
    public BaseResp findAll(Integer page, Integer size) {
        Boolean exists=redisTemplate.hasKey("shop");
        if (exists){
            System.out.println("redis");
            int start=(page-1)*size;
            List shop = redisTemplate.opsForList().range("shop", start, start + size - 1);
            long total=redisTemplate.opsForList().size("shop");
            return new BaseResp(0,"ok",shop,total);
        }else {
            System.out.println("数据库");
            List<Shop> list=shopRepository.findAll();
            redisTemplate.opsForList().leftPushAll("shop",list);
            PageRequest of = PageRequest.of(page-1, size);
            Page<Shop> all = shopRepository.findAll(of);
            return new BaseResp(0,"ok",all.getContent(),all.getTotalElements());
        }
    }
}
